package com.wash.shoes.controller.pc;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.wash.shoes.common.enums.WriteOffStatusEnum;
import com.wash.shoes.domain.mtbusy.MtCallbackEnum;
import com.wash.shoes.domain.mtbusy.MtCallbackFactory;
import com.wash.shoes.domain.vo.MtPushMessage;
import com.wash.shoes.entity.MtCallBlackPo;
import com.wash.shoes.entity.OrderPo;
import com.wash.shoes.mapper.OrderMapper;
import com.wash.shoes.service.MtCallBlackService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @author lijianguo
 * @Date 11/09/2024
 * <p>
 * 美团回调的call,不需要权限申请
 **/
@Api(tags = {"PC-美团回调"})
@RequestMapping({"/mtCallBack"})
@RestController
public class MtCallBackController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger("mt-record");

    @Resource
    HttpServletRequest httpServletRequest;

    @Autowired
    MtCallBlackService mtCallBlackService;

    @Autowired
    MtCallbackFactory mtCallbackFactory;

    //https://developer.meituan.com/docs/msg/msg_ddzh_c08eb5f3-ba98-4c97-8579-7d95757df2b4
    @ApiOperation("美团回调接口5810001-取消预订")
    @PostMapping(value = "5810001")
    R<String> mtCallBack5810001() {

        MtPushMessage message = createMtMessage();
        log.info("美团回调接口5810001-取消预订 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        saveMtRecord(message, "美团回调接口5810001-取消预订");
        mtCallbackFactory.call(MtCallbackEnum.MT_5810001, message, getKhLastToken(String.valueOf(message.getDeveloperId())), message.getDeveloperId().toString());
        return createSucR();
    }

    @ApiOperation("美团回调接口5810003-预订结果同步")
    @PostMapping(value = "5810003")
    R<String> mtCallBack5810003() {

        MtPushMessage message = createMtMessage();
        log.info("美团回调接口5810003-预订结果同步 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        saveMtRecord(message, "美团回调接口5810003-预订结果同步");

        return createSucR();
    }

    @ApiOperation("美团回调接口5810007-改约结果通知三方")
    @PostMapping(value = "5810007")
    R<String> mtCallBack5810007() {

        MtPushMessage message = createMtMessage();
        log.info("美团回调接口5810007-改约结果通知三方 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        saveMtRecord(message, "美团回调接口5810007-改约结果通知三方");

        return createSucR();
    }

    @ApiOperation("美团回调接口5810009-到家行业库存查询")
    @PostMapping(value = "5810009")
    R<String> mtCallBack5810009() {

        MtPushMessage message = createMtMessage();
        log.info("美团回调接口5810009-到家行业库存查询 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        saveMtRecord(message, "美团回调接口5810009-到家行业库存查询");

        return createSucR();
    }

    @ApiOperation("美团回调接口5810015-改约提交")
    @PostMapping(value = "5810015")
    ResponseEntity<String> mtCallBack5810015() {
        try {
            MtPushMessage message = createMtMessage();
            log.info("美团回调接口5810015-改约提交 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            saveMtRecord(message, "美团回调接口5810015-改约提交");
            mtCallbackFactory.call(MtCallbackEnum.MT_5810015, message, getKhLastToken(String.valueOf(message.getDeveloperId())), message.getDeveloperId().toString());
            return ResponseEntity.ok(JSON.toJSONString(createSucR()));
        } catch (Exception e) {
            log.error("{}", e);
            log.error("改约失败：", e);
            return ResponseEntity.ok(JSON.toJSONString(createErrorR(e.getMessage())));
        }
    }

    @ApiOperation("美团回调接口5810017-开始预订")
    @PostMapping(value = "5810017")
    ResponseEntity<String> mtCallBack5810017() {
        try {
            MtPushMessage message = createMtMessage();
            log.info("美团回调接口5810017-开始预订 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
            saveMtRecord(message, "美团回调接口5810017-开始预订");
            mtCallbackFactory.call(MtCallbackEnum.MT_5810017, message,
                    getKhLastToken(String.valueOf(message.getDeveloperId())), message.getDeveloperId().toString());
            return ResponseEntity.ok(JSON.toJSONString(createSucR()));
        } catch (Exception e) {
            log.error("{}", e);
            log.error("预订失败：", e);
            return ResponseEntity.ok(JSON.toJSONString(createErrorR(e.getMessage())));
        }
    }

    @ApiOperation("美团回调接口5810027-通知三方核销")
    @PostMapping(value = "5810027")
    R<String> mtCallBack5810027() {

        MtPushMessage message = createMtMessage();
        log.info("美团回调接口5810027-通知三方核销 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        saveMtRecord(message, "美团回调接口5810027-通知三方核销");
        //mtCallbackFactory.call(MtCallbackEnum.MT_5810031, message, getKhLastToken());

        try {
            cn.hutool.json.JSONObject jsonObject = JSONUtil.parseObj(message.getMessage());
            String orderId = jsonObject.get("orderId").toString();//获取美团的订单id
            //根据美团orderid 查询订单
            if (StringUtils.isNotEmpty(orderId)) {
                OrderPo orderPo = orderMapper.getByMtOrderId(orderId);
                if (Objects.nonNull(orderPo)) {
                    orderPo.setDyVerificationTime(new Date());//设置核销时间
                    orderPo.setWriteOffStatus(WriteOffStatusEnum.WRITE_OFF);//设置核销状态
                    orderMapper.updateById(orderPo);
                }
            }
        } catch (Exception e) {
            log.error("美团回调接口5810027-通知三方核销,message:" + message, e);
        }

        return createSucR();
    }

    @Autowired
    private OrderMapper orderMapper;

    @ApiOperation("美团回调接口5810031-预订核销同步")
    @PostMapping(value = "5810031")
    R<String> mtCallBack5810031() {

        MtPushMessage message = createMtMessage();
        log.info("美团回调接口5810031-预订核销同步 {}", JSONObject.toJSONString(message, SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue));
        saveMtRecord(message, "美团回调接口5810031-预订核销同步");
        mtCallbackFactory.call(MtCallbackEnum.MT_5810031, message,
                getKhLastToken(String.valueOf(message.getDeveloperId())), message.getDeveloperId().toString());

        return createSucR();
    }

    @ApiOperation("美团回调接口健康检查")
    @GetMapping(value = "mtHealth")
    R<String> mtHealth() {
        log.info("美团回调接口健康检查....");
        return createSucR();
    }

    private R<String> createSucR() {
        R r = R.ok("suc", "suc");
        r.setCode(0);
        return r;
    }

    private R<String> createErrorR(String msg) {
        R r = R.ok(msg, "error");
        r.setCode(1);
        return r;
    }


    /**
     * @author lijianguo
     * @Date 12/09/2024
     * 保存美团回调的记录
     **/
    private void saveMtRecord(MtPushMessage message, String remark) {
        MtCallBlackPo mtCallBlackPo = new MtCallBlackPo();
        BeanUtil.copyProperties(message, mtCallBlackPo);
        mtCallBlackPo.setRemark(remark);
        mtCallBlackService.save(mtCallBlackPo);
    }

    private MtPushMessage createMtMessage() {
        MtPushMessage mtMessage = new MtPushMessage();
        String msgType = httpServletRequest.getParameter("msgType");
        String timestamp = httpServletRequest.getParameter("timestamp");
        String sign = httpServletRequest.getParameter("sign");
        String developerId = httpServletRequest.getParameter("developerId");
        String businessId = httpServletRequest.getParameter("businessId");
        String msgId = httpServletRequest.getParameter("msgId");
        String opBizCode = httpServletRequest.getParameter("opBizCode");
        String ePoiId = httpServletRequest.getParameter("ePoiId");
        String message = httpServletRequest.getParameter("message");
        if (StringUtils.isNotEmpty(msgType)) {
            mtMessage.setMsgType(Integer.parseInt(msgType));
        }
        if (StringUtils.isNotEmpty(timestamp)) {
            mtMessage.setTimestamp(Long.parseLong(timestamp));
        }
        mtMessage.setSign(sign);
        if (StringUtils.isNotEmpty(developerId)) {
            mtMessage.setDeveloperId(Integer.parseInt(developerId));
        }
        if (StringUtils.isNotEmpty(businessId)) {
            mtMessage.setBusinessId(Integer.parseInt(businessId));
        }
        mtMessage.setMsgId(msgId);
        mtMessage.setOpBizCode(opBizCode);
        mtMessage.setEPoiId(ePoiId);
        mtMessage.setMessage(message);
        return mtMessage;
    }
}
